package com.zlm.pc;

/**
 * @Author: 郑
 * 生产者消费者synchronized实现
 *
 */
public class PcDemo1 {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"a").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"b").start();
    }
}

// 判断等待 业务 通知
class Data{
    //数字资源
    private int num = 0;

    // +1
    public synchronized void increment() throws InterruptedException {

        if(num !=0){
            //等待
            this.wait();
        }
        //业务
        num++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知
        this.notifyAll();
    }
    // -1
    public synchronized void decrement() throws InterruptedException {
         if(num !=1){
             //等待
             this.wait();
         }
         //业务
         num--;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
         //通知
        this.notifyAll();
    }
}
